const workerpool = require('workerpool');
const path = require('path');
const fs = require('fs')
const pool = workerpool.pool(
    path.join(__dirname + '/createWorker.js'),
    {
        workerType: 'process', // process创建独立进程,thread创建独立线程
        maxWorkers: 8, // 最大线程数
    });

async function run(fileName, userFolder) {
    const task_count = userFolder.length;
    let completedTasks = 0;// 记录完成的任务数量,用于输出进度信息
    try {
        const promises = [];
        for (let taskId = 0; taskId < task_count; taskId++) {
            const promise = pool.exec('createFiles', [{ fileName, userId: userFolder[taskId] }])
                .then(result => {
                    completedTasks++;
                    process.send({ all: task_count, current: completedTasks || 1, progress: true })//将进度传给封装的命令文件
                    console.log(`任务完成: ${userFolder[taskId]}文件夹汇总中...${completedTasks}/${task_count}`);
                })
                .catch(err => {
                    console.error(`任务失败: [线程_${taskId}]:`, err.message);
                });
            promises.push(promise);
        }

        await Promise.all(promises);
        process.send({ progress: false })

        // 关闭线程池
        await pool.terminate();
    } catch (err) {
        console.error('任务执行出错:', err);
        await pool.terminate();
    }
}

process.on('message', (msg) => {
    const folder = `upload-tool(node)/static/${msg.fileName.split('.')[0]}`
    const userFolder = fs.readdirSync(`../${folder}/数据整理`)
    run(msg.fileName, userFolder);
})